package com.sayice.icepusher.controller;

import com.huawei.services.runtime.Context;
import com.huawei.services.runtime.entity.apig.APIGTriggerEvent;
import com.huawei.services.runtime.entity.apig.APIGTriggerResponse;
import com.sayice.icepusher.cache.CacheService;
import com.sayice.icepusher.config.WeiXinConfig;
import com.sayice.icepusher.service.WeiXinMessageService;
import com.sayice.icepusher.util.encrypt.WXBizMsgCrypt;
import com.sayice.icepusher.util.thread.ThreadPoolUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.sayice.icepusher.service.WeiXinMessageService.botSend;

/**
 * @author shubing
 */
public class MessageController {
    /**
     * suite_ticket正则
     */
    private static final Pattern SUITE_TICKET_PATTERN = Pattern.compile("<SuiteTicket><!\\[CDATA\\[(.+)]]></SuiteTicket>");
    
    /**
     * 临时授权码正则
     */
    private static final Pattern AUTH_CODE_PATTERN = Pattern.compile("<AuthCode><!\\[CDATA\\[(.+)]]></AuthCode>");
    
    /**
     * 初始化函数，获取环境变量
     */
    public void init(Context context) {
        CacheService.CACHE_URL = context.getUserData("cache_url");
        WeiXinConfig.OPEN_CORP_ID = context.getUserData("open_corpid");
        WeiXinConfig.SUITE_ID = context.getUserData("suite_id");
        WeiXinConfig.SUITE_SECRET = context.getUserData("suite_secret");
        WeiXinConfig.PERMANENT_CODE = context.getUserData("permanent_code");
        WeiXinConfig.APP_TOKEN = context.getUserData("app_token");
        WeiXinConfig.APP_AGENT_ID = context.getUserData("app_agentid");
        WeiXinConfig.OPEN_USER_ID = context.getUserData("open_userid");
        WeiXinConfig.AES_KEY = context.getUserData("aes_key");
        WeiXinConfig.BOT_WEBHOOK = context.getUserData("bot_webhook");
    }
    
    /**
     * 入口函数，处理请求
     */
    public APIGTriggerResponse handle(APIGTriggerEvent event, Context context) {
        String path = event.getPathParameters().get("");
        String httpMethod = event.getHttpMethod();
        Map<String, String> queryParams = event.getQueryStringParameters();
        // 响应字符串
        String respStr = "";
        switch (path) {
            case "callback":
                try {
                    WXBizMsgCrypt wxcpt;
                    String msgSignature = queryParams.get("msg_signature");
                    String timestamp = queryParams.get("timestamp");
                    String nonce = queryParams.get("nonce");
                    String echostr = queryParams.get("echostr");
                    if ("GET".equals(httpMethod)) {
                        wxcpt = new WXBizMsgCrypt(WeiXinConfig.APP_TOKEN, WeiXinConfig.AES_KEY, "");
                        respStr = wxcpt.VerifyURL(msgSignature, timestamp, nonce, echostr);
                    } else if ("POST".equals(httpMethod)) {
                        wxcpt = new WXBizMsgCrypt(WeiXinConfig.APP_TOKEN, WeiXinConfig.AES_KEY, WeiXinConfig.SUITE_ID);
                        String rawBody = event.getRawBody();
                        String sMsg = wxcpt.DecryptMsg(msgSignature, timestamp, nonce, rawBody);
                        ThreadPoolUtils.executorService.execute(() -> {
                            Matcher ticketMatch;
                            Matcher authCodeMatch;
                            if ((ticketMatch = SUITE_TICKET_PATTERN.matcher(sMsg)).find()) {
                                String suiteTicket = ticketMatch.group(1);
                                CacheService.set("suiteTicket", suiteTicket);
                                // 推送 suite_ticket
                                botSend("suiteTicket: " + suiteTicket);
                            } else if ((authCodeMatch = AUTH_CODE_PATTERN.matcher(sMsg)).find()) {
                                // 临时授权码
                                String authCode = authCodeMatch.group(1);
                                // 获取并推送企业授权信息
                                botSend(WeiXinMessageService.getAuthInfo(authCode).toString());
                            }
                        });
                        respStr = "success";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    respStr = e.getMessage();
                }
                break;
            case "msg/text":
                respStr = WeiXinMessageService.sendText(queryParams.get("content"));
                break;
            default:
                break;
        }
        Map<String, String> headers = new HashMap<>(2);
        headers.put("Content-Type", "application/json");
        return new APIGTriggerResponse(200, headers, respStr);
    }
}
